登录 白背景

https://leetcode-cn.com/problems/merge-k-sorted-lists/

效率偏低的解法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        lists = [x for x in lists if x]
        if not lists or not lists[0]:
            return None
        i = lists[0].val
        for l in lists:
            if l.val < i:
                i = l.val
        newNode = ListNode(0)
        ret = newNode
        while True:
            # print('i',i)
            for o in range(len(lists)):
                # print('  lists[o]',lists[o])
                if lists[o]:
                    while lists[o] and lists[o].val == i:
                        # print('    lists[o]',lists[o],ret)
                        ret.next = ListNode(lists[o].val)
                        ret = ret.next
                        lists[o] = lists[o].next
                else:
                    lists[o] = None
            
            if len(lists) == lists.count(None):
                break
            i += 1
        return newNode.next